package org.lab.data;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.lab.io.IDownloader;



public class Ticker {
	private IDownloader downloader;
	private DateUtil dateUtil;
	private QuoteUtil quoteUtil;
	private LinkedList<Quote> quotes;
	private Map<Date, Quote> quotesMap;
	
	public Ticker(IDownloader downloader) {
		this.downloader = downloader;
		this.setDateUtil(new DateUtil(this));
		this.setQuoteUtil(new QuoteUtil(this));
		importData();
	}
	
	void importData() {
		try {
			setQuotes(downloader.importData());
			HashMap<Date, Quote> tempMap = new HashMap<Date, Quote>();
			for(Quote quote:quotes){
				tempMap.put(quote.getDate(), quote);
			}
			quotesMap = Collections.unmodifiableMap(tempMap);
		} catch (IOException e) {
			e.printStackTrace();
			setQuotes(null);
		}
	}

	void setQuotes(LinkedList<Quote> quotes) {
		this.quotes = quotes;
	}

	public List<Quote> getQuotes() {
		return quotes;
	}

	public List<Quote> getQuotes(Date initialDate) {
		int initial = quotes.indexOf(quotesMap.get(initialDate));
		return (List<Quote>) quotes.subList(initial, quotes.size());
	}

	public List<Quote> getQuotes(Date initialDate, Date endDate) {
		try {
			int initial = quotes.indexOf(quotesMap.get(initialDate));
			int last = quotes.indexOf(quotesMap.get(endDate));
			return (LinkedList<Quote>) quotes.subList(initial, last);
		} catch (Exception ex) {
			return null;
		}
	}

	public List<Quote> getQuotes(Date initialDate, int numQuotes) {
		try {
			int initial = quotes.indexOf(quotesMap.get(initialDate));
			return (List<Quote>) quotes.subList(initial, initial+numQuotes);
		} catch (Exception ex) {
			return null;
		}
	}

	public List<Quote> getQuotes(int numQuotes) {
		try {
			return (List<Quote>) quotes.subList(0, numQuotes);
		} catch (Exception ex) {
			return null;
		}
	}

	public void setDateUtil(DateUtil dateUtil) {
		this.dateUtil = dateUtil;
	}

	public DateUtil getDateUtil() {
		return dateUtil;
	}

	public void setQuoteUtil(QuoteUtil quoteUtil) {
		this.quoteUtil = quoteUtil; 
	}

	public QuoteUtil getQuoteUtil() {
		return quoteUtil;
	}

	public Map<Date, Quote> getQuotesMap() {
		return quotesMap;
	}

	public Quote getQuote(Date testDate) {
		return quotesMap.get(testDate);
	}
	
}
